package vip.specimen.system.common.implement;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import org.springframework.stereotype.Component;
import vip.specimen.system.datasource.entity.SystemAliPayEntity;
import vip.specimen.system.datasource.entity.SystemTrade;
import vip.specimen.system.service.SystemAliPayConfigService;
import vip.specimen.system.utils.connector.PayService;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * *@Author: 余浪人
 * *@Date：2021/3/31 10:34
 * *@Email:yulangren520@Gmail.com
 * *@QQ:1368419640
 **/
@Component
public class AliPay implements PayService {
    @Resource
    SystemAliPayConfigService aliPayConfigService;
    private SystemAliPayEntity config = null;
    private AlipayClient alipayClient = null;
    private static AliPay aliPay;

    @PostConstruct
    public void init() {
        aliPay = this;
        aliPay.config = aliPay.aliPayConfigService.getConfig();
        aliPay.alipayClient = new DefaultAlipayClient(
                aliPay.config.getServerURL(),
                aliPay.config.getAppId(),
                aliPay.config.getAppPrivateKey(),
                "json", "utf-8",
                aliPay.config.getAliPayPublicKey(), "RSA2"
        );
    }

    @Override
    public JSONObject create(SystemTrade trade) throws AlipayApiException {
        JSONObject param = new JSONObject();
        param.put("out_trade_no", trade.getOutTradeNo());
        param.put("total_amount", trade.getTotalAmount());
        param.put("subject", trade.getSubject());
        param.put("store_id", trade.getStoreId());
        param.put("timeout_express", trade.getTimeoutExpress() + "m");
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizContent(param.toJSONString());
        JSONObject result = (JSONObject) param.clone();
        param.clear();
        AlipayTradePrecreateResponse response = aliPay.alipayClient.execute(request);
        result.put("isSuccess", response.isSuccess());
        result.put("qrCode", response.getQrCode());
        result.put("msg", response.getSubMsg());

        return result;
    }

    @Override
    public JSONObject query(String outTradeNo) throws AlipayApiException {
        JSONObject json = new JSONObject();
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();//创建API对应的request类
        json.put("out_trade_no", outTradeNo); // 系统订单编号 （二选一）//todo 参数格式化（封装）
        json.put("trade_no", "");// 支付宝订单编号
        request.setBizContent(json.toJSONString()); //设置业务参数
        AlipayTradeQueryResponse response = aliPay.alipayClient.execute(request);
        System.out.print(response.getBody());
//        response.
        return null;
    }

    @Override
    public JSONObject close(String outTradeNo) throws AlipayApiException {
        AlipayTradeCloseRequest request = new AlipayTradeCloseRequest();
        request.setBizContent("{" +
                "\"trade_no\":\"2013112611001004680073956707\"," +
                "\"out_trade_no\":\"HZ0120131127001\"," +
                "  }");
        AlipayTradeCloseResponse response = aliPay.alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public JSONObject refund() throws AlipayApiException {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"20150320010101001\"," +
                "\"trade_no\":\"2014112611001004680073956707\"," +
                "\"refund_amount\":200.12," +
                "\"refund_currency\":\"USD\"," +
                "\"refund_reason\":\"正常退款\"," +
                "\"out_request_no\":\"HZ01RF001\"," +
                "\"operator_id\":\"OP001\"," +
                "\"store_id\":\"NJ_S_001\"," +
                "\"terminal_id\":\"NJ_T_001\"," +
                "      \"goods_detail\":[{" +
                "        \"goods_id\":\"apple-01\"," +
                "\"alipay_goods_id\":\"20010001\"," +
                "\"goods_name\":\"ipad\"," +
                "\"quantity\":1," +
                "\"price\":2000," +
                "\"goods_category\":\"34543238\"," +
                "\"categories_tree\":\"124868003|126232002|126252004\"," +
                "\"body\":\"特价手机\"," +
                "\"show_url\":\"http://www.alipay.com/xxx.jpg\"" +
                "        }]," +
                "      \"refund_royalty_parameters\":[{" +
                "        \"royalty_type\":\"transfer\"," +
                "\"trans_out\":\"2088101126765726\"," +
                "\"trans_out_type\":\"userId\"," +
                "\"trans_in_type\":\"userId\"," +
                "\"trans_in\":\"2088101126708402\"," +
                "\"amount\":0.1," +
                "\"amount_percentage\":100," +
                "\"desc\":\"分账给2088101126708402\"" +
                "        }]," +
                "\"org_pid\":\"2088101117952222\"," +
                "      \"query_options\":[" +
                "        \"refund_detail_item_list\"" +
                "      ]" +
                "  }");
        AlipayTradeRefundResponse response = aliPay.alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public JSONObject cancel() throws AlipayApiException {
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"20150320010101001\"," +
                "\"trade_no\":\"2014112611001004680073956707\"" +
                "  }");
        AlipayTradeCancelResponse response = aliPay.alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public JSONObject refundQuery() throws AlipayApiException {
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        request.setBizContent("{" +
                "\"trade_no\":\"20150320010101001\"," +
                "\"out_trade_no\":\"2014112611001004680073956707\"," +
                "\"out_request_no\":\"2014112611001004680073956707\"," +
                "\"org_pid\":\"2088101117952222\"," +
                "      \"query_options\":[" +
                "        \"refund_detail_item_list\"" +
                "      ]" +
                "  }");
        AlipayTradeFastpayRefundQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

    @Override
    public JSONObject billDownload() throws AlipayApiException {
        AlipayDataDataserviceBillDownloadurlQueryRequest request = new AlipayDataDataserviceBillDownloadurlQueryRequest();
        request.setBizContent("{" +
                "\"bill_type\":\"trade\"," +
                "\"bill_date\":\"2016-04-05\"" +
                "  }");
        AlipayDataDataserviceBillDownloadurlQueryResponse response = aliPay.alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return null;
    }

}
